#!/usr/bin/env python3

import subprocess
import time
import statistics

# 定义 webbench 命令
webbench_command = "webbench -c 9900 -t 60 http://127.0.0.1:9000/hello"

# 存储每次测试的响应时间
response_times = []

# 测试次数，多次测试以获得更可靠的结果
test_count = 5

for _ in range(test_count):
    try:
        start_time = time.time()
        # 执行 webbench 命令
        subprocess.run(webbench_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
        end_time = time.time()
        # 计算本次测试的响应时间
        response_time = end_time - start_time
        response_times.append(response_time)
    except subprocess.CalledProcessError as e:
        print(f"Webbench 执行出错: {e.stderr.decode('utf-8').strip()}")
    except subprocess.TimeoutExpired:
        print("测试超时，跳过此次结果。")

# 计算统计数据
if response_times:
    average_response_time = statistics.mean(response_times)
    min_response_time = min(response_times)
    max_response_time = max(response_times)

    print(f"平均响应时间: {average_response_time:.2f} 秒")
    print(f"最小响应时间: {min_response_time:.2f} 秒")
    print(f"最大响应时间: {max_response_time:.2f} 秒")
else:
    print("未获取到有效的响应时间数据。")